#include "BreakPointFile.h"
#include <cassert>
#include "Util.h"
#include <fstream>

IBreakPointFile::IBreakPointFile(const std::string & fileName)
: _fileName(fileName) {
  if(!util::File::exists(fileName)){
    util::File::create(fileName);
  }
}
IBreakPointFile::~IBreakPointFile(){
}



BreakPointFileAsBinary::BreakPointFileAsBinary(const std::string & fileName) 
: IBreakPointFile(fileName) {
}

BreakPointFileAsBinary::~BreakPointFileAsBinary(){
}

int BreakPointFileAsBinary::load(){
  int no = 0;
  int ret =util::File::readAsBinary(getFileName(), &no); 
  return (ret > 0) ? no : 0; //NOTE: read failed -> return 0;
}

int BreakPointFileAsBinary::save(int no){
  int ret = util::File::writeAndFlushAsBinary(getFileName(), no);
  return ret > 0 ? 0 : -1;
}


static void test_breakpoint_BinaryFormat(){

	const char * fileName = "breakpoint.binary.file";
	util::File::remove(fileName);

	IBreakPointFile * file = new BreakPointFileAsBinary(fileName);
	assert(util::File::exists(fileName));

	assert(0 == file->load());

	assert(0 == file->save(1));

  delete file;
}


BreakPointFileAsText::BreakPointFileAsText(const std::string & fileName)
: IBreakPointFile(fileName) {
}
BreakPointFileAsText::~BreakPointFileAsText() {
}

int BreakPointFileAsText::load() {
  std::ifstream ifs(getFileName(), std::ios_base::in);
  if(!ifs.is_open()){
    return -1;
  }
  int number = 0;
  ifs >> number;
  return number;
}

int BreakPointFileAsText::save(int no) {
  std::ofstream ofs(getFileName(), std::ios_base::out);
  if(!ofs.is_open()){
    return -1;
  }
  std::string str = std::to_string(no);
  ofs << str;
  ofs.flush();
  return 0;
}



static void test_breakpoint_TextFormat(){
	const char * fileName = "breakpoint.text.file";
  util::File::remove(fileName);

  IBreakPointFile * file = new BreakPointFileAsText(fileName);
  assert(util::File::exists(fileName));
  assert(0 == file->load());
  assert(0 == file->save(1));
  assert(1 == file->load());
  assert(0 == file->save(2));
  assert(2 == file->load());
  delete file;
}

void test_breakpoint_file(){
  test_breakpoint_TextFormat();
  test_breakpoint_BinaryFormat();
}


